//
//  PicCollectionView.swift
//  JIMWeiBo
//
//  Created by 陈恒均 on 2018/2/13.
//  Copyright © 2018年 陈恒均. All rights reserved.
//

import UIKit
import SDWebImage

class PicCollectionView: UICollectionView {

    var picURLS : [NSURL] = [NSURL](){
        didSet{
            self.reloadData()
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        delegate = self
        dataSource = self
    }
    
}

extension PicCollectionView : UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picURLS.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PicCell", for: indexPath) as! PicCollectionViewCell
        
        cell.picURL = picURLS[indexPath.item]
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let userInfo = [ShowPhotoBrowserIndexKey : indexPath , ShowPhotoBrowserUrlsKey : picURLS] as [String : Any]
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: ShowPhotoBrowserNote), object: self, userInfo: userInfo)
    }

}

extension PicCollectionView : AnimatorForPresentDelegate
{
    func startRect(indexPath: NSIndexPath) -> CGRect {
        let cell = self.cellForItem(at: indexPath as IndexPath)
        let startFrame = self.convert((cell?.frame)!, to: UIApplication.shared.keyWindow)
        
        return startFrame
        
    }
    
    func endRect(indexPath: NSIndexPath) -> CGRect {
        let picURL = picURLS[indexPath.item]
        let image = SDWebImageManager.shared().imageCache?.imageFromCache(forKey: picURL.absoluteString)
        
        let w = UIScreen.main.bounds.width
        let h = w / (image?.size.width)! * (image?.size.height)!
        var y : CGFloat = 0
        if h > UIScreen.main.bounds.height {
            y = 0
        }else{
            y = (UIScreen.main.bounds.height - h) * 0.5
        }
        return CGRect(x: 0, y: y, width: w, height: h)
        
        
    }
    
    func imageView(indexPath: NSIndexPath) -> UIImageView {
        let imageView = UIImageView()
        
        let picURL = picURLS[indexPath.item]
        
        let image = SDWebImageManager.shared().imageCache?.imageFromCache(forKey: picURL.absoluteString)
        
        imageView.image = image
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        
        return imageView
        
    }
    
    
}


